package com.pig4cloud.pig.common.core.util;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 浮点数计算工具类
 *
 * @Author: hjl
 * @Date: 2021/6/22 15:37
 */
@Slf4j
public class BigDecimalUtil {

	/**
	 * 计算百分率
	 * @param numerator 分子
	 * @param denominator 分母
	 * @return
	 */
	public static BigDecimal getRatio(BigDecimal numerator, BigDecimal denominator){
		try {
			if (Objects.isNull(numerator) || Objects.isNull(denominator) || numerator.compareTo(BigDecimal.ZERO) == 0|| denominator.compareTo(BigDecimal.ZERO) == 0) {
				return BigDecimal.ZERO;
			}
			return numerator.divide(denominator, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}
	public static BigDecimal getRatio(Integer numerator, Integer denominator){
		try {
			return getRatio(new BigDecimal(numerator), new BigDecimal(denominator));
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}
	public static BigDecimal getRatio(Long numerator, Long denominator){
		try {
			return getRatio(new BigDecimal(numerator), new BigDecimal(denominator));
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}

	/**
	 * 求商
	 * @param numerator
	 * @param denominator
	 * @return
	 */
	public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator){
		return divide(numerator, denominator, 2);
	}
	public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator, int scale){
		try {
			//BigDecimal比较大小，避免多个小数点个数的时候会不相等，导致除数为0
			if (Objects.isNull(numerator) || Objects.isNull(denominator) ||numerator.compareTo(BigDecimal.ZERO) == 0 || denominator.compareTo(BigDecimal.ZERO) == 0) {
				return BigDecimal.ZERO;
			}
			return numerator.divide(denominator, scale, BigDecimal.ROUND_HALF_UP);
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}
	public static BigDecimal divide(Integer numerator, Integer denominator){
		return divide(numerator, denominator, 2);
	}
	public static BigDecimal divide(Integer numerator, Integer denominator, int scale){
		try {
			return divide(new BigDecimal(numerator), new BigDecimal(denominator), scale);
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}
	public static BigDecimal divide(Long numerator, Long denominator){
		return divide(numerator, denominator, 2);
	}
	public static BigDecimal divide(Long numerator, Long denominator, int scale){
		try {
			return divide(new BigDecimal(numerator), new BigDecimal(denominator), scale);
		} catch (Exception e) {
			log.error("计算百分率异常", e);
		}
		return BigDecimal.ZERO;
	}
}
